/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package my.cbr.gui;

import com.toedter.calendar.JDateChooser;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import jcolibri.cbrcore.CBRCase;
import jcolibri.cbrcore.CBRQuery;
import jcolibri.util.FileIO;
import my.cbr.application.CBRApplication;
import my.cbr.casedescriptions.CaseDescription;
import my.cbr.database.CaseGenerator;
import my.cbr.database.model.ApproximationNumber;
import my.cbr.database.model.AquacultureProdUnit;
import my.cbr.database.model.measurement.MeasurementType;
import my.cbr.database.model.measurement.OxygenInstance;
import my.cbr.database.model.measurement.TemperatureInstance;
import my.cbr.utils.LinearApproximation;
import my.cbr.utils.Utility;

/**
 *
 * @author Marte
 */
public class QueryDialog extends JDialog{
    
    private JLabel backgroundImage;
    private TextField sending;
    private TextField recieving;
    private TextField site;
    private JDateChooser dateChooser;
    private TextField starvationDays;
    
    private JLabel vaccine;
    private JLabel hatchery;
    private JLabel origin;
    private JLabel capacity;
    private JLabel individCount;
    private JLabel currentTemp;
    private JButton tempTrend;
    private JLabel currentOxygen;
    private JButton oxyTrend;
    private JLabel info;

    private CaseDescription query;
    private boolean hasQuery = false;
   

    public QueryDialog(JFrame parent)
    {
        super(parent, true);
        
        configureFrame();            
    }

    public void reSetFrame()
    {
        sending.setText("");
        recieving.setText("");
        site.setText("");
        
        starvationDays.setText("");
        vaccine.setText("");
        hatchery.setText("");
        origin.setText("");
        capacity.setText("");
        individCount.setText("");
        currentTemp.setText("");
        tempTrend.setText("Click to visualize");
        tempTrend.setEnabled(false);
        currentOxygen.setText("");
        oxyTrend.setText("Click to visualize");
        oxyTrend.setEnabled(false);
        info.setText("");

    }
    
    private void configureFrame()
    {
        try{
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            }catch (Exception e1){}


        this.setTitle("Set Query");
        this.backgroundImage = new JLabel();
        this.backgroundImage.setIcon(new ImageIcon(FileIO.findFile("my/cbr/gui/images/queryCase.png")));
        this.getContentPane().setLayout(new BorderLayout());		
        this.getContentPane().add(backgroundImage, BorderLayout.WEST);
        
        JPanel panel = new JPanel();
        panel.setLayout(new SpringLayout());

        JLabel label;
        panel.add(label = new JLabel("Sending production units"));
        label.setToolTipText("separate the units with commas");
        panel.add(sending = new TextField());

        panel.add(new JLabel("Recieving production unit"));
        panel.add(recieving = new TextField());

        panel.add(new JLabel("Aquaculture Site"));
        panel.add(site = new TextField());

        panel.add(new JLabel("Capacity of site"));
        panel.add(capacity = new JLabel());

        panel.add(new JLabel("Individ Count in sending unit"));
        panel.add(individCount = new JLabel());

        panel.add(new JLabel("Number of starvation days"));
        panel.add(starvationDays = new TextField());

        String dateFormat = "yyyy-MM-dd";
        dateChooser = new JDateChooser(new Date());
        dateChooser.setDateFormatString(dateFormat);
        panel.add(label = new JLabel("Operation Date"));
        panel.add(dateChooser);

        panel.add(new JLabel("Vaccines"));
        panel.add(vaccine = new JLabel());

        panel.add(new JLabel("Hatcheries"));
        panel.add(hatchery = new JLabel());

        panel.add(new JLabel("Species Origins"));
        panel.add(origin = new JLabel());

        panel.add(new JLabel("Current Temperature"));
        panel.add(currentTemp = new JLabel());

        panel.add(new JLabel("Temperature Trend"));
        panel.add(tempTrend = new JButton());
        tempTrend.setText("Click to visualize");
        tempTrend.setToolTipText("Click to visualize");
        tempTrend.setEnabled(false);
        tempTrend.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                JLabel temp = Utils.createJFreeChart(query.getTemperature(), "Temperature");
                JDialog jDialog = new JDialog(QueryDialog.this);
                jDialog.add(temp);
                jDialog.pack();
                jDialog.setVisible(true);
            }
        });

        panel.add(new JLabel("Current Oxygen Level"));
        panel.add(currentOxygen = new JLabel());

        panel.add(new JLabel("Oxygen Trend"));
        panel.add(oxyTrend = new JButton());
        oxyTrend.setText("Click to visualize");
        oxyTrend.setToolTipText("Click to visualize");
        oxyTrend.setEnabled(false);
        oxyTrend.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                JLabel temp = Utils.createJFreeChart(query.getOxygen(), "Oxygen");
                JDialog jDialog = new JDialog(QueryDialog.this);
                jDialog.add(temp);
                jDialog.pack();
                jDialog.setVisible(true);

            }
        });

        panel.add(new JLabel("Note"));
        panel.add(info = new JLabel());
        
        //Lay out the panel.
	Utils.makeCompactGrid(panel,
		                15, 2, //rows, cols
		                6, 6,        //initX, initY
		                9, 9);       //xPad, yPad


        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new BorderLayout());
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        buttonPanel.add(panel, BorderLayout.NORTH);
        
        JPanel buttons = new JPanel();
        buttons.setLayout(new BorderLayout());

        JButton setQueryButton = new JButton("Set Query");
        setQueryButton.setBackground(Color.red);
        setQueryButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                if(!hasQuery)
                {
                    info.setText("Get all attributes before seting the query");
                }
                else
                {
                    setQuery();
                }
            }
        });

        JButton exitButton = new JButton("Exit");
        exitButton.setForeground(Color.CYAN);
        exitButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				try {
					CBRApplication.getInstance().postCycle();
				} catch (Exception ex) {
					org.apache.commons.logging.LogFactory.getLog(CBRApplication.class).error(ex);
				}
				System.exit(-1);
			}
		});
        JButton getFullQueryButton = new JButton("Get all attributes");
        getFullQueryButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                try{
                    try {
                        getWholeQuery();
                        hasQuery = true;
                    } catch (ParseException ex) {
                        org.apache.commons.logging.LogFactory.getLog(QueryDialog.class.getName()).error(ex);
                    }
                }catch (ClassNotFoundException ex) {
                    org.apache.commons.logging.LogFactory.getLog(QueryDialog.class.getName()).error(ex);
                }catch (SQLException ex) {
                    org.apache.commons.logging.LogFactory.getLog(QueryDialog.class.getName()).error(ex);
                }
            }
        });

        buttons.add(setQueryButton, BorderLayout.CENTER);
        buttons.add(exitButton, BorderLayout.EAST);
        buttons.add(getFullQueryButton, BorderLayout.WEST);

        buttonPanel.add(buttons, BorderLayout.EAST);
                
        this.getContentPane().add(buttonPanel, BorderLayout.CENTER);
        
        this.setSize(650, 510);
//		this.setResizable(false);
		Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
		setBounds((screenSize.width - this.getWidth()) / 2,
			(screenSize.height - this.getHeight()) / 2,
			getWidth(),
			getHeight());
        
    }

    public void getWholeQuery() throws ClassNotFoundException, SQLException, ParseException
    {
        List<Integer> sendingProdUnits = new ArrayList<Integer>();
        List<Integer> numOfStartvationDays = new ArrayList<Integer>();
        Integer recievingProdUnit = 0;
        Integer prodSite = 0;
      
        try{
            StringTokenizer st = new StringTokenizer(this.sending.getText(), ", ");
        
            while(st.hasMoreTokens())
            {
                sendingProdUnits.add(Integer.parseInt(st.nextToken()));
                System.out.println(sendingProdUnits.get(sendingProdUnits.size()-1));
            }
            st = new StringTokenizer(this.starvationDays.getText(), ", ");

            while(st.hasMoreTokens())
            {
                numOfStartvationDays.add(Integer.parseInt(st.nextToken()));
            }

            //setting default values for starving days if
            int units = sendingProdUnits.size();
            int enteredDays = numOfStartvationDays.size();
            if(enteredDays < units)
            {
                for(int i=enteredDays; i < units; i++)
                {
                    numOfStartvationDays.add(14);
                }
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(dateChooser.getDate());
        
            CaseGenerator gen = new CaseGenerator();
        
            prodSite = Integer.parseInt(site.getText());
            recievingProdUnit = Integer.parseInt(recieving.getText());

            //generate case query from database
            CBRCase caseQuery = gen.generateQueryCase(sendingProdUnits, numOfStartvationDays, recievingProdUnit, format, prodSite);
            query = (CaseDescription) caseQuery.getDescription();
            System.out.println(query.toString());

        }catch(NumberFormatException e)
        {
            info.setText("Wrong input, try again");
            org.apache.commons.logging.LogFactory.getLog(QueryDialog.class.getName()).error(e);
            return;
        }

        vaccine.setText(Utility.getString(query.getReceivingProdUnit().getVaccine().toArray()));
        hatchery.setText(Utility.getString(query.getReceivingProdUnit().getHatcheryCompanyID().toArray()));
        origin.setText(Utility.getString(query.getReceivingProdUnit().getSpeciesOrigin().toArray()));
        capacity.setText(query.getAquacultureSite().getCapacity().toString());
        String count = "";
        for(AquacultureProdUnit prodSending : query.getSendingProdUnits())
        {
            count += prodSending.getIndividCount()+"   ";
        }
        individCount.setText(count);

        try{

            MeasurementType<TemperatureInstance> temperature = query.getTemperature();
            if(temperature.getCurrentInstance().getValue()==null)
                currentTemp.setText("null");
            else
            {
                String current = temperature.getCurrentInstance().getValue().toString();
                currentTemp.setText(current+" C");
            }

            LinearApproximation approx = new LinearApproximation(-0.3,0.4); //the variation of the slope, only set statically in query
            ApproximationNumber num = approx.applyLinearApproximation(Utility.listOfMeasurementInstanceToDoubleArray(query.getTemperature().getPastInstances()));
            query.getTemperature().setTrend(approx.getTrend(num));
            tempTrend.setText(approx.getTrend(num));
            tempTrend.setEnabled(true);
            }catch(NullPointerException e){
                info.setText("Temperature instances missing");
                org.apache.commons.logging.LogFactory.getLog(QueryDialog.class.getName()).error(e);
            }

        try{
            MeasurementType<OxygenInstance> oxygen = query.getOxygen();
            if(oxygen.getCurrentInstance().getValue()==null)
                currentOxygen.setText("null");
            else{
                String current = oxygen.getCurrentInstance().getValue().toString();
                currentOxygen.setText(current+" %");
            }

            LinearApproximation approx = new LinearApproximation(-6.0, 2.0); //the variation of the slope, only set statically in query
            ApproximationNumber num = approx.applyLinearApproximation(Utility.listOfMeasurementInstanceToDoubleArray(query.getOxygen().getPastInstances()));
            query.getOxygen().setTrend(approx.getTrend(num));
            oxyTrend.setText(approx.getTrend(num));
            oxyTrend.setEnabled(true);
            }catch(NullPointerException e){
                info.setText("Missing oxygen instances");
                org.apache.commons.logging.LogFactory.getLog(QueryDialog.class.getName()).error(e);
            }

        info.setText("Input OK");
      
    }

    public void setQuery()
    {
        this.setVisible(false);
    }

    public CBRQuery getQuery()
    {
        CBRQuery cbrquery = new CBRQuery();
        cbrquery.setDescription(query);
        
        return cbrquery;

    }
    public static void main(String[] args) {
		QueryDialog qf = new QueryDialog(null);
		qf.setVisible(true);
		System.out.println("Bye");
	}



}
